Repository navigation
Provider: reversible add-on hold — stay connected, leave routing, unload models (local IPC for add-ons) - #1620
Conversation
While a local add-on (the Darkbloom Sandbox VM host) uses the Mac, the provider stays registered on its coordinator connection, leaves routing and returns on the same connection when released. - Drain owner `addonHold`: update, reconnect and model-switch drains can neither replace nor reopen it; only a stop preempts it. The hold never sends `provider_drain` and never stops the App Attest worker. Planned reconnects run beneath the hold and the fresh `register` keeps it. - Hold: close admission, announce `status: draining` with optional `busy_reason` / `busy_since_ms` / `busy_addon` (heartbeat and register, both register encoders), finish accepted work within 120 s, unload every model and free retained KV segments and the MLX buffer cache. Release reopens admission, re-probes capacity, sends an idle/serving heartbeat and replays deferred `desired_models`. - Leases of 30-600 s; an expired lease ends the hold only when no add-on holds `ownership.lock`. Active holds persist owner-only so a restarted or updated provider comes back held before any model can load. - `hold.v1` on `~/.darkbloom/runtime/addon.sock` (0700/0600): newline JSON, 8 KiB limit, hello/hold/status/renew/release, per-request audit-token code-signature check (io.darkbloom.sandbox, team SLDQ2GJ6TL, hardened runtime, same UID; DEBUG builds may add one explicit identity). - `darkbloom addon status|hold|release` through the lifecycle mailbox, Autopilot busy reason `addon_hold`, local structured transition logs, and the status line for a held provider. - Docs (architecture, IPC reference, protocol, CLI, configuration, Autopilot, tests), threat model TB-012/A-018/T-059, changelog fragment.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
…rnals Behavior-preserving refactor pass over the add-on hold: - The CLI validates --lease-seconds against the provider's own bounds (AddonHoldControlRequest.leaseSecondsRange) instead of a copied literal; the provider drops an out-of-range request unanswered. The CLI's answer timeout is named once. Help and error text are unchanged. - AddonHoldBook owns its machine-lock keep set: a renewal clears it and the lease check asks the book whether a keep is new. - AddonIPCServer builds the socket address for bind and connect in one helper and names its write timeout. - AddonHoldControlRequest.isValid documents its actual 60 s window (the comment wrongly cited the drain request's).
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Threat model review — advisoryReviewed head Reviewers: anthropic/claude-sonnet-5.5: first pass completed; anthropic/claude-opus-5.5: selected depth completed (35 batches); openai/gpt-6.1-sol: selected depth completed (30 batches) LOW: New add-on local IPC/mailbox control channel is not covered by the threat modelprovider-swift/Sources/ProviderCore/Addon/AddonPeerPolicy.swift:57 · TB-003 This PR adds a local control surface that can close serving admission, cancel in-flight inference after 120s, and unload every model. Callers are code-signature-authenticated sockets (AddonPeerPolicy.authenticate) and the operator mailbox (handleAddonControl). No TB/T entry covers this boundary: socket location and permissions, per-connection versus per-request authentication, lease bounds, or the rule that an expired lease is kept while the machine lock is held (ProviderLoop+AddonHold.swift:322-334, 142-146). The lock appears to be observed through a plain file, so any same-UID process that takes it could keep the provider held indefinitely. The same-UID user is already the operator (ADV-001), so this is an availability and documentation gap rather than a confidentiality regression. Fix: add a TB entry and threat for the add-on hold, recording the peer policy, lease clamps, machine-lock semantics and fail-open on an unreadable hold record (ProviderLoop+AddonHold.swift:366-368). Raised by: anthropic/claude-sonnet-5.5 LOW: New add-on hold IPC surface cites an undefined threat-model boundary (TB-012)docs/reference/addon-hold-ipc.md:94 · TB-002, TB-003 docs/reference/addon-hold-ipc.md documents a new local AF_UNIX `hold.v1` control surface (~/.darkbloom/runtime/addon.sock). Over it, a code-signed add-on can make the provider drain or hold serving capacity, and an expired lease is kept while the add-on holds ownership.lock. The doc points readers to threat-model `TB-012` (line 96), but the base canonical model defines boundaries only through TB-011. No asset, threat or mitigation covers this boundary. Nothing in the model covers the same-user peer-token and code-requirement check, the DEBUG-only `DARKBLOOM_ADDON_DEV_IDENTITY` acceptance, the `DARKBLOOM_ADDON_SOCKET` path override, or the indefinite availability hold through ownership.lock. The new `darkbloom addon` lifecycle-mailbox commands in cli-reference.md are also unmodeled. Trigger: a reviewer relies on TB-012 to evaluate this surface, but no TB-012 exists. Impact: provider availability and drain controls stay unreviewed against TB-003 and TB-002. The model also does not record that busy fields reported to the coordinator are self-reported. Fix: add TB-012 and its threats to docs/threat-model.yaml. The new entries should record that the socket is not a boundary against the same user. They should state whether release builds honor DARKBLOOM_ADDON_SOCKET. They should also bound how long a hold can persist. Raised by: anthropic/claude-opus-5.5 MEDIUM: Unauthenticated connections can exhaust all add-on IPC slotsprovider-swift/Sources/ProviderCore/Addon/AddonIPCServer.swift:128 · new attack surface Connections enter the eight-slot connection set before peer authentication, which occurs only after a complete request line arrives (lines 155–158 and 186–189). An unsigned same-UID program can open eight sockets and send nothing, denying service to the legitimate signed add-on for the 300-second idle timeout; reconnecting repeats the denial. The signature policy therefore does not protect availability of hold, status, release, or renewal operations. Authenticate the kernel peer token before admitting a connection, and bound incomplete-request time independently of received-byte activity. Raised by: openai/gpt-6.1-sol LOW: Hold-record validation can block indefinitely on a FIFOprovider-swift/Sources/ProviderCore/Addon/AddonHoldStore.swift:26 · TB-003 read() opens the hold-record path in blocking mode before checking that it is a regular file. A same-UID process can replace addon-hold.json with a FIFO containing no writer; open() then blocks indefinitely, so the subsequent fstat validation never returns .invalid. O_NOFOLLOW does not prevent this. This exposes the persisted-hold reader to a local availability attack whenever restoration reads the record. Open with O_NONBLOCK, then validate the descriptor as a regular file before reading. Raised by: openai/gpt-6.1-sol Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging. Scan completed; human review required. Coverage: 249/249 source units; cross-file integration complete. 0 selected depth batch(es) pending. All threat definitions indexed; relevant full definitions selected. Unchanged callers are not scanned. Cost this run: $0.0000 reported, $0.0000 reserved with unknown cost; 0 paid request(s), 66 reused batch(es), 0 provider cache-hit tokens. Saved findings and earlier report · Historical findings are not confirmed resolved. Bedrock: 48 request(s), 867194 uncached + 0 cache-read + 948304 cache-write input / 35169 output tokens; 0 request(s) with unknown usage. OpenRouter backup used 0 time(s). Dollar amounts above cover OpenRouter only; AWS billing is reconciled separately. |
# Conflicts: # docs/developer/test.md
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3332b520aa
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e164315dc4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Brings in #1615, #1618 (provider 0.10.3 hotfix), #1617, #1619 and #1620 (reversible add-on hold). Conflicts and resolutions: - docs/provider/cli-reference.md: only the "Last updated" stamp conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one 2026-10-27 stamp; both texts are kept (this branch's served-count lines and master's `darkbloom addon` section merged cleanly). No semantic interplay with #1620: the served counts and the add-on hold's "Not serving: held by add-on" status line are independent.
Brings in #1615, #1618 (provider 0.10.3 hotfix), #1617, #1619 and #1620 (reversible add-on hold). Conflicts and resolutions: - docs/provider/cli-reference.md: only the "Last updated" stamp conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one 2026-10-27 stamp; both texts are kept. - docs/reference/protocol-messages.md: only the "Last updated" stamp conflicted. Kept the one 2026-10-27 stamp; this branch's no-session drain text and master's busy_reason/busy_since_ms/busy_addon fields merged cleanly. provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift merged cleanly: #1620 changes beginServingDrain and the lifecycle monitor, this branch only the end of performLifecycleDrain (coordinatorSettled). Interplay with #1620, reviewed: an add-on hold keeps its registered connection, so the stop path still waits for the coordinator's drain acknowledgement while held; only a stop without a registered session skips it. A planned reconnect under a hold goes through the bounded handshake, and its fresh register still carries the busy fields.
Brings in #1615, #1618 (provider 0.10.3 hotfix), #1617, #1619 and #1620 (reversible add-on hold). Conflicts and resolutions: - provider-swift/Sources/ProviderCore/Service/DaemonState+Coding.swift: both sides appended a daemon-state key to the same CodingKeys line (`coordinatorConnection` here, `addonHold` from #1620). Kept both as `case autopilotState, coordinatorConnection, addonHold`, matching the struct's field order and the encode order. The decode/encode bodies merged cleanly; both keys stay optional (decodeIfPresent and encodeIfPresent), so files from older daemons still decode and older readers ignore the new keys. - docs/provider/cli-reference.md: only the "Last updated" stamp conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one 2026-10-27 stamp; both texts are kept (this branch's Traffic line and master's `darkbloom addon` section). DaemonStateFile.swift and ProviderLoop+Trust.swift merged cleanly: the DaemonState initializer takes coordinatorConnection before appAttest and addonHold last, and writeDaemonState passes both in that order.
… holds the Mac With master's add-on hold (#1620) merged, a held provider stays connected and authorized but leaves routing on purpose (status: draining). The traffic verdict ignored the hold: `darkbloom status` printed "Not serving: held by add-on ..." followed by "Traffic: eligible for coordinator work (App Attest authorized until ...)", doctor passed `coordinator traffic`, and once the lease lapsed or a reconnect under the hold went unconfirmed both reported "NOT receiving coordinator work" with an authorization cause and a `darkbloom restart` fix, which a hold survives. ServingReadiness.verdict now returns no verdict while an add-on holds a connected Mac, so status omits the Traffic line (as it does beside a drain line) and doctor skips the check. A disconnect is still reported. Re-registration needed no change: superviseServingAuthorization already waits while autopilotBusyReasons() is non-empty, which includes addon_hold. Tests (fail on the merge commit, pass here): - ServingReadinessTests.aConnectionAnAddonHoldsHasNoVerdict - StatusCommandRunTests.heldProviderHasNoTrafficVerdict Docs: cli-reference (Traffic line), troubleshooting (coordinator traffic row); changelog fragment coordinator-traffic-verdict.md updated in place.
Brings in #1615, #1618 (provider 0.10.3 hotfix), #1617, #1619 and #1620 (reversible add-on hold). Conflicts and resolutions: - docs/architecture/model-autopilot.md: only the "Last updated" stamp conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one 2026-10-27 stamp; both texts are kept (this branch's selected-model recovery sections and master's `addon_hold` busy reason). - docs/provider/cli-reference.md: only the "Last updated" stamp conflicted. Kept the one 2026-10-27 stamp; both texts are kept. Code merged cleanly, including ProviderLoop+AutopilotBusy.swift (the recovery attempt counts as `preload`; #1620 adds `addon_hold`), DaemonState+Coding.swift (selectedModelRecovery and addonHold keys) and ProviderLoop+ModelLoading.swift (an unload makes waiting recoveries due; an add-on hold's unload keeps the persisted serving set). Interplay with #1620, reviewed: a recovery check pauses while the hold owns admission (servingDrain.refusing), and the hold's unload pass waits for a running attempt (modelSwitchMutationsSettled). The hold did not cancel an attempt already loading; the next commit fixes that.
…load in progress With master's add-on hold (#1620) merged, a selected-model recovery check pauses while the hold owns admission, but an attempt that was already loading kept going: enterAddonHold cancelled coordinator preloads only. The hold's unload pass waits for loads at most addonHoldSettleTimeout (60 s) and then marks the Mac held, so a longer recovery load (a large model) could finish and install its slot after the add-on was told the models were unloaded, beside its VMs. A shorter one was loaded only to be unloaded again, and its entry left the recovery queue. enterAddonHold now also cancels selectedModelRecovery.attempt, exactly as it cancels preloadTasks. The load path honours cancellation before it installs a slot, the attempt treats CancellationError as "keep waiting", so the model stays queued and is retried after the release. Test (fails on the merge commit after 13 s: "the recovery load kept running under the hold"; passes here in 0.2 s): - SelectedModelRecoveryPolicyTests.anAddonHoldCancelsTheAttemptInProgress Docs: addon-hold.md invariant 5, model-autopilot.md recovery section; changelog fragment selected-models-recover.md updated in place.
…regression Brings in the M5 head-dim split attention hotfix (#1618: libs/mlx 31f550af, libs/mlx-swift 4926d3d9) and the add-on hold (#1620). Without the hotfix, Gemma 4 26B prefill of 1,024 or more tokens exits on M5 GPUs, so qualification builds of this branch must include it. Conflicts were the "Last updated" lines in docs/provider/cli-reference.md and docs/reference/configuration.md; master's 2026-10-27 is kept. The branch's diff against master is unchanged: the Gemma QAT exact acceptance default, its config comment, tests, docs and changelog fragment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…oundation Master's reversible add-on hold adds a busy field to registration and heartbeat beside this branch's cluster fields. Every conflict keeps both: Register carries the member role, nonce, cluster models and membership and then busy; Heartbeat carries cluster_session and then busy; the codec, registration sender and client state pass both; the protocol reference lists both. Startup keeps the control-only member's skipped catalog prewarm and takes master's refusingForServiceChange, so an add-on hold at startup does not shut the provider down. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…restoration fix Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nto the cluster beta Brings master's reversible add-on hold through #1407's resolution (cluster fields and busy side by side in registration and heartbeat). Only the freshness stamps of three reference pages conflicted here; they take the later date. Gitlinks unchanged: libs/mlx ea318ee0, libs/mlx-swift 31ffa0d, libs/mlx-swift-lm b6650465. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The merge adds #1615, #1617, #1618 (provider 0.10.3 hotfix), #1619 and #1620 (reversible add-on hold) to this branch. Conflicts and resolutions: - docs/provider/cli-reference.md: only the "Last updated" stamp had a conflict (2026-10-26 on this branch, 2026-10-27 on master). The merge keeps one stamp, 2026-10-27. It keeps the two texts: the reconnect rows of this branch in the runtime constants, and the `darkbloom addon` section and the add-on runtime row of master. - docs/reference/protocol-messages.md: only the "Last updated" stamp had a conflict. The merge keeps one stamp, 2026-10-27. Git put the "Add-on hold busy fields" section of master and the "Close codes and the reconnect wait" section of this branch one after the other, after "Provider lifecycle drain". The file has each section one time. Git merged all code without a conflict. Only CoordinatorClientState.swift changed on the two sides. Master adds the ProviderState.busy property. This branch adds the CoordinatorSessionRecorder class. These changes are in different types. The new code of master does not call the symbols that this branch changes: ExponentialBackoff.nextDelay(), the private functions in CoordinatorClient+Connection.swift and MockCoordinator.dropActiveWebSocket. The gitlinks are those of master: libs/mlx 31f550af, libs/mlx-swift 4926d3d9, libs/mlx-swift-lm aee6ebb6. Against master, the branch has the same changes as before, except the two stamps. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Brings in #1615, #1617, #1618 (provider 0.10.3 hotfix), #1619, #1620 and #1623 (add-on hold), #1621 (Qwen JSON response formats without default thinking) and #1622 (Qwen JSON response_format answers under the JSON grammar). Conflicts and resolutions: - docs/architecture/inference.md: only the "Last updated" stamp conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one 2026-10-27 stamp; both texts are kept (this branch's forced-admission table and whitespace rule, and master's constrained Qwen JSON answer sections, merged cleanly). Interplay with #1621 and #1622 (same Qwen 3.5/3.6 families): - QwenJSONAnswerPolicy installs the JSON grammar only for requests with no tools and no tool_choice, so a forced request keeps this branch's prompt-forced, withheld and post-validated path with no token constraint, also when it carries a JSON response_format. - templateAdditionalContext turns thinking off for forced legacy Qwen before #1621's JSON default is consulted; both give enable_thinking=false, and caller controls stay overridden on the forced path as before. - NativeToolStreamRouter drops framing whitespace only when a tool call is required. A constrained JSON answer is never forced, so its bytes, including whitespace, stream unchanged.
…er a connection left unauthorized (#1607) * Say why a connected provider gets no coordinator work, and re-register when it is never authorized A provider can stay connected, heartbeating and passing legacy challenges while the coordinator refuses to route to it: no App Attest lease and no legacy authorization. Public /v1/stats showed 74-79 of ~1,150 connections (about 7%) in that state in every snapshot from 2026-10-25 17:06Z to 2026-10-26 05:18Z, many for more than 11 hours. `darkbloom status` showed them as healthy, or as `Trust: awaiting coordinator status`, so operators restarted blindly or asked whether they were banned. - ServingReadiness turns the daemon state into a verdict: eligible, not yet (just connected), or not receiving coordinator work with the cause and a fix: disconnected (with the registration count, which exposes a reconnect loop), no coordinator verdict 90 s after connecting, an expired App Attest lease, or the coordinator's reason for not authorizing the connection, refined by the local App Attest observation (stalled Apple call, macOS below 27, App Attest unavailable outside the GUI session, locked keychain, no linked account). - `darkbloom status` prints it as a `Traffic:` line with `→ fix:`, and `darkbloom doctor` as the `coordinator traffic` check. - The daemon state file records the coordinator connection (`coordinator_connection`: connected, since, connections). - The provider re-registers, through the existing planned-reconnect drain, a connection the coordinator has not authorized for 15 min plus a 0-15 min per-process jitter, then after 30 min, 1 h, 2 h and every 4 h, never with accepted work, a load, a drain, an update or a model switch. A new registration starts a new coordinator verification session, which clears coordinator states that only a reconnect cleared. Public log lines record when routing stops, resumes and each re-registration. * Test the doctor coordinator traffic check for unauthorized and authorized connections * Keep the disconnect time across failed reconnects; re-register only while idle Refactor pass on the serving-readiness change. - noteCoordinatorConnection reset `since` on every `.disconnected` event. The client reports one per failed reconnect attempt (up to every 30 s), so `Traffic:` read "disconnected 20s ago" through an hour-long outage. A disconnect while already down now keeps `since`. - A re-registration closes admission before it disconnects, which fails an accepted Autopilot command and cancels a startup preload. It now waits for the idle test the Autopilot inventory re-registration uses (no accepted Autopilot command and no Autopilot busy reason, a superset of the earlier checks) and still never starts during an update. - The "authorizes this connection" log line no longer fires when the models were withdrawn while the connection was unauthorized; the re-registration line says "at least 15 min". - A local App Attest signing or bundle problem now gets the install-script reinstall that doctor's `app signing` check gives; `update` leaves a current version in place. - `shouldReconnect(workInProgress:)` is now `busy:`, and the policy enum is internal: only ProviderCore and its tests use it. - The status traffic test moves to the end of its suite, away from the served-count test another branch inserts at the same place. * Merge follow-up (#1620 interplay): no traffic verdict while an add-on holds the Mac With master's add-on hold (#1620) merged, a held provider stays connected and authorized but leaves routing on purpose (status: draining). The traffic verdict ignored the hold: `darkbloom status` printed "Not serving: held by add-on ..." followed by "Traffic: eligible for coordinator work (App Attest authorized until ...)", doctor passed `coordinator traffic`, and once the lease lapsed or a reconnect under the hold went unconfirmed both reported "NOT receiving coordinator work" with an authorization cause and a `darkbloom restart` fix, which a hold survives. ServingReadiness.verdict now returns no verdict while an add-on holds a connected Mac, so status omits the Traffic line (as it does beside a drain line) and doctor skips the check. A disconnect is still reported. Re-registration needed no change: superviseServingAuthorization already waits while autopilotBusyReasons() is non-empty, which includes addon_hold. Tests (fail on the merge commit, pass here): - ServingReadinessTests.aConnectionAnAddonHoldsHasNoVerdict - StatusCommandRunTests.heldProviderHasNoTrafficVerdict Docs: cli-reference (Traffic line), troubleshooting (coordinator traffic row); changelog fragment coordinator-traffic-verdict.md updated in place. --------- Co-authored-by: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com>
…r another model blocked them A selected model left cold by memory (skipped by the startup preload, or unloaded by an Autopilot operation to place another model) is retried from the capacity tick until it is resident again, evicting only idle models outside the selection within Autopilot's victim rules. `darkbloom status` says why it waits and when a saved `enabled_models` differs from the running selection. Shutdown waits at most 15 s per unload instead of forever for a slot whose native retirement never finishes. Rebased onto dev as one commit (was 17 commits plus four master merges on master). The merges carried the #1606 drain and #1620 add-on hold resolutions, so the branch's net change is re-applied instead of replaying each commit. Resolved against dev: #1730's operator model filter (`operatorModelFilter`) is kept beside this PR's `savedEnabledModels` and `enabledModelsAtLastSwitch`; `DaemonState.registeredModels` is kept beside the new optional keys; the add-on hold calls dev's `publishBusy()`; the recovery invariant in model-autopilot.md is numbered 11 after dev's operator-filter invariant 10.
…r another model blocked them A selected model left cold by memory (skipped by the startup preload, or unloaded by an Autopilot operation to place another model) is retried from the capacity tick until it is resident again, evicting only idle models outside the selection within Autopilot's victim rules. `darkbloom status` says why it waits and when a saved `enabled_models` differs from the running selection. Shutdown waits at most 15 s per unload instead of forever for a slot whose native retirement never finishes. Rebased onto dev as one commit (was 17 commits plus four master merges on master). The merges carried the #1606 drain and #1620 add-on hold resolutions, so the branch's net change is re-applied instead of replaying each commit. Resolved against dev: #1730's operator model filter (`operatorModelFilter`) is kept beside this PR's `savedEnabledModels` and `enabledModelsAtLastSwitch`; `DaemonState.registeredModels` is kept beside the new optional keys; the add-on hold calls dev's `publishBusy()`; the recovery invariant in model-autopilot.md is numbered 11 after dev's operator-filter invariant 10.
Warning
Merging this publishes provider releases automatically. A push to
masterthat touchesprovider-swift/**runs.github/workflows/release-swift.yml, which builds, signs (Developer ID) and publishes a dev release and a staging release in parallel (prod still needs a signedvX.Y.Ztag). Owner review is required before merge; this PR is a draft and requests no reviewers.Summary
While a Mac runs Darkbloom Sandbox VMs (the separately installed add-on
io.darkbloom.sandbox, teamSLDQ2GJ6TL), the provider can now be held: it stays registered on its coordinator connection, leaves routing, finishes accepted work, unloads every model, and returns on the same connection the moment the add-on releases it. Naming is add-on neutral (addon) in provider code and on the wire.Behavior
holdaddonHoldcloses admission (coordinator and local).ProviderState.busyis published and an event heartbeat goes out at once withstatus: "draining"plus busy fields. Coordinatorload_model/prefetch_modelget the existing draining failure;desired_modelsis deferred; auto-update, Autopilot, revisions and MTP upgrades are deferred.drainingaddonHoldDrainTimeoutDefault = .seconds(120)(the background update's budget); anything left is then cancelled. Load transitions get 60 s to settle.heldunloadModel; retained KV segments and the MLX buffer cache are released.loaded-models.jsonis kept, as on shutdown, so the next start's preload plan is unchanged.releaseidle/servingheartbeat goes out immediately, and a deferreddesired_modelssnapshot is replayed. Models load on demand.~/.darkbloom/runtime/ownership.lockwith a non-blocking sharedflock; it auto-releases only if no add-on holds the lock exclusively. Running VMs keep the Mac held.~/.darkbloom/runtime/addon-hold.json(0600). A restarted or updated provider closes admission before the local endpoint or startup preload can load anything, while a lease is valid or the lock is held.Hazards from the review, handled:
provider_drainbarrier for a hold. The hold never sends it. An update or App Attest stall restart whose drain the hold took over stops before its barrier (waitForSafeDisconnect(underAddonHold:)). The App Attest worker is never stopped by a hold and can recover from an update stop while held (ProviderDrain.refusingForServiceChange).ProviderDrain.beginrefuses to letupdate/reconnect/modelSwitchreplaceaddonHold(onlylifecyclepreempts it); a planned reconnect runs beneath the hold, the freshregistercarries the busy fields, andfinishPlannedReconnectre-announces draining. A reconnect still pending at release keeps admission closed until its registration (resumeAfterAddonHold).run()'s pre-registration abort checks now userefusingForServiceChange, so a restored hold no longer looks like a stop.Wire fields (optional, backward compatible)
registerandheartbeatgainbusy_reason(closed vocabulary:addon),busy_since_ms(Unix ms the oldest hold began) andbusy_addon(signer identifier, oroperatorfor the CLI). They are omitted when not held, sent on heartbeats only besidestatus: "draining", and mirrored on the raw-attestation register path. Unknownbusy_reasonvalues decode as absent. Coordinator support lands separately in darkbloom-platform; coordinators onmasteralready exclude a provider onstatus: "draining", refresh that mark on every draining heartbeat (150 s TTL) and clear it on the release heartbeat, and they ignore unknown provider keys. Autopilot's closedbusy_reason(s)vocabulary gainsaddon_hold(reported instead ofdrainingfor the hold's own drain).IPC contract (
hold.v1)Socket
~/.darkbloom/runtime/addon.sock(dir0700, socket0600;DARKBLOOM_ADDON_SOCKETfor tests only). Newline-delimited JSON, ≤ 8 KiB per message, one response line per request, several requests per connection (≤ 8 connections, 300 s idle close).{"v":1,"op":"hello"}{"v":1,"ok":true,"capabilities":["hold.v1"],"provider_version":"x.y.z"}{"v":1,"op":"hold","addon":"io.darkbloom.sandbox","vm_bytes":N,"lease_seconds":30..600}{"v":1,"ok":true,"hold_id":"<uuid>","state":"draining"|"held","since_ms":N,"lease_expires_at_ms":N}— idempotent, one active hold per add-on{"v":1,"op":"status","hold_id":"..."}{"v":1,"ok":true,"state":"draining"|"held"|"released"|"expired","since_ms":N,"lease_expires_at_ms":N}{"v":1,"op":"renew","hold_id":"...","lease_seconds":30..600}{"v":1,"ok":true,"state":...,"lease_expires_at_ms":N}{"v":1,"op":"release","hold_id":"..."}{"v":1,"ok":true,"state":"released"}{"v":1,"ok":false,"error":"unauthorized"|"unsupported_version"|"invalid_request"|"not_found"|"unavailable"}Full reference:
docs/reference/addon-hold-ipc.md; mechanism and invariants:docs/architecture/addon-hold.md.Add-on client: Layr-Labs/darkbloom-sandbox#23 implements the same contract. It takes
ownership.lockexclusively before holding (workers inherit the descriptor, so the lock outlives a crashed agent until its VMs are gone), sendsholdwith a 60 s lease, pollsstatusuntilheld, renews every 20 s, and treatsheldas no inference in flight and models unloaded — exactly the provider'sheldtransition here. It re-holds onnot_found/released/expired. Its socket-path override keepsownership.lockbeside the socket;DARKBLOOM_ADDON_SOCKEThere does the same (lock and hold record move to the socket's directory), so test setups agree. Interplay to note from that PR: its control plane waits 15 s for an allocation, while this provider's drain may take up to 120 s plus unload; a slow drain declines that one allocation and the next one finds the Mac held.Security notes
TB-012,A-018,T-059.LOCAL_PEERTOKENaudit token → same effective UID →SecCodeCopyGuestWithAttributes(kSecGuestAttributeAudit)(token incl. pidversion, never a PID or path) → requirementanchor apple generic and identifier "io.darkbloom.sandbox" and certificate 1[field.1.2.840.113635.100.6.2.6] and certificate leaf[field.1.2.840.113635.100.6.1.13] and certificate leaf[subject.OU] = "SLDQ2GJ6TL"+ team/identifier + hardened runtime. Theaddonfield must equal the verified signer; peers only see their own holds. Unauthenticated peers getunauthorizedand are disconnected.#if DEBUGbuilds may add one explicitDARKBLOOM_ADDON_DEV_IDENTITY=TEAMID:identifier(e.g.P7373SVQX6:io.darkbloom-test.sandbox); release builds compile without it.O_NOFOLLOW+ uid/mode checks; a live socket is never taken over; framing, connection count and idle time are bounded. Local transition logs ({"operation":"addon_hold",...}on stderr) carry no hold IDs, request IDs, models or content.Operator CLI
darkbloom addon [status],darkbloom addon hold [--lease-seconds 30..600](holds asoperator),darkbloom addon release [--force](refuses while the machine lock is held unless forced). They use the same-UID lifecycle mailbox bound to the live process identity.darkbloom statusprintsNot serving: held by add-on ….Before / After
Before — behavior
flowchart LR classDef actor fill:#dbeafe,stroke:#1d4ed8,color:#0f172a classDef bad fill:#fee2e2,stroke:#b91c1c,color:#0f172a classDef neutral fill:#f1f5f9,stroke:#475569,color:#0f172a A["Sandbox add-on wants the Mac"]:::actor --> B{"Free the memory?"}:::neutral B -- "darkbloom stop" --> C["Drain + provider_drain barrier"]:::neutral --> D["Disconnect: offline, no earnings"]:::bad D --> E["Return = restart: new registration, authorization, warm-up"]:::bad B -- "do nothing" --> F["VMs compete with resident models"]:::badAfter — behavior
Before — code flow
After — code flow
Validation
macOS 27.0.1 (26A434), Xcode Swift 6.4, Apple Silicon; state isolated as in
scripts/run-provider-tests.sh. Commite32528cis signed and Verified on GitHub.make provider-teststeps on basead7dd816e:swift build --build-tests,scripts/stage-test-metallib.sh,scripts/run-provider-tests.shwith the documented fixtures (prepare-mimo-provider-fixtures.py,prepare-mimo-prompt-fixtures.py)ProviderCoreFoundationTests.PageCacheTests.testHashingDropsPagesThatWereCachedBeforeTheRead(OS page residency after hashing: 33554432 ≠ 0). That target depends only onProviderBuildEnvironmentandProviderCoreFoundation, untouched here; it passed 3/3 in isolation before and after the rebase (load-sensitive flake)make provider-test:test_protocol_fixture_resources.py,test-stage-test-metallib.py,test-stage-swiftpm-resource-bundles.py0af5e1c86(0.10.3 hotfix: host-onlyjit_kernels.cpp; tree-keyed metallib digest unchanged), rebuilt, then every touched suite: the new suites plusProviderLifecycleTests,ProviderModelSwitchTests,UpdateDrainAwarenessTests,AutoUpdateCycleTests,AppAttestUpdateLifecycleTests,StartupPreloadTests,StandaloneStartupPreloadTests,LifecycleMailboxTests,ModelSlotBookkeepingTests,RetirementGateTests,TransitionWatchdogTests,ServeLoop{Connection,Dispatch,AppAttest,ColdLoad}Tests,ProviderAuthorizationConnectionTests,Coordinator{Client,Integration,ModelSwitch}Tests,HeartbeatIdlePolicyTests,CapacityEventHeartbeatTests,ProtocolTests,AppAttestResumeTransportTests,NativeMediaToolsCapabilityTests,Autopilot{SnapshotCoding,Adoption,BusyReason}Tests,CLIDispatchTests,StatusCommand*,SwitchCommand*,WatchdogTests,DaemonState*,PageCacheTestsPageCacheTests3/3make changelog-check,make changelog-preview,make docs-check,make docs-impact-check BASE=origin/mastergit diff --checkcleanNew tests (51, all passing), in
provider-swift/Tests/ProviderCoreTests/Addon/andprovider-swift/Tests/DarkbloomCLITests/AddonCommandTests.swift:AddonHoldDrainOwnershipTests,AddonHoldLoopTests.updateDrainAndReconnectCannotReopenAHold,aStopTakesOverAndNoNewHoldIsAcceptedWhileStopping).busy_*, noprovider_drainframe, 503drainingrejection while held,requestPlannedReconnect→ secondregisterwithbusy_*, release →idleheartbeat without them (AddonHoldServeLoopTests).flock), restart restore (valid lease, expired + lock held, expired + free), unload-all with the preload set kept and the App Attest worker untouched, bounded drain, resume + deferreddesired_modelsreplay, operator mailbox (AddonHoldLoopTests).AddonIPCTests); real socket permissions, several requests per connection, oversized line, unauthenticated peer refused by the real Security-framework policy, stale vs live socket (AddonIPCServerTests); owner-only record and lock probe (AddonHoldStoreTests); production requirement string compiles and refuses the test process (AddonPeerPolicyTests).ProviderBusyWireTests); CLI parsing/rendering and daemon-state round trip (AddonCommandTests).Not run: interop with a real signed
io.darkbloom.sandboxbuild (no signed add-on on this runner; the socket and serve-loop flows inject an authenticator, the peer policy is tested negatively); GPU/full-model qualification (unaffected by this change).Limitations and follow-ups
busy_*(immediate exclusion onregister, dashboards) is separate darkbloom-platform work; until then the draining status alone excludes the provider, and a request that races a fresh registration gets the typed draining 503.io.darkbloom.sandbox) is not exercised in CI; tests use the real policy negatively and an injected authenticator for the socket/serve flows. Physical interop with the add-on is a separate check.get-task-allowand library-validation exemptions in release builds.~/.darkbloom-dev/runtime/addon.sock, …), so the add-on'ssocket_pathmust point there to hold a dev install; production is exactly~/.darkbloom/runtime/….unavailable) while a model switch owns admission; leases use wall-clock time (the lock fallback covers running VMs).3332b52(signed, Verified), behavior-preserving. Changes: the CLI validates--lease-secondsagainst the provider's own bounds (AddonHoldControlRequest.leaseSecondsRange, fromAddonHold.leaseSecondsRange) instead of a copied30...600(the provider drops an out-of-range request unanswered) and names its 10 s answer timeout once; help and error text are byte-identical.AddonHoldBookowns its machine-lock keep set (recordRenewal,keepForMachineLock).AddonIPCServerbuilds the socket address forbindandconnectin one helper (withAddress) and names its write timeout. TheAddonHoldControlRequest.isValidcomment cited the drain request's window; it now documents the actual 60 s window (drain and switch requests allow 3605 s; behavior unchanged, so confirm 60 s is intended). Reviewed and left as is: drain-owner precedence, planned reconnect andresumeAfterAddonHold, the startuprefusingForServiceChangechecks, wire encoders, peer policy, IPC framing. Rerun after the change:swift build --build-tests(no new warnings),scripts/stage-test-metallib.sh, the add-on selector (51 tests: 47 in 9 suites + 4 in 1), every touched suite listed above with the documented MiMo provider fixtures (406 tests / 56 suites and 30 / 7 passed; XCTest 0 failures,PageCacheTests3/3),make changelog-check,make docs-check,make docs-impact-check BASE=origin/master,git diff --check: all pass. WithoutMIMO_V26_SERIAL_LOAD_FIXTURESthe two "genuine strict scanner quote" startup tests fail at fixture lookup, as documented.Need help on this PR? Tag
@codesmith-botwith what you need.